#include "loginwindow.h"
#include "ui_loginwindow.h"
#include "mainwindow.h"
#include <QFile>
#include <QTextStream>
#include <QMessageBox>

LoginWindow::LoginWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::LoginWindow)
{
    ui->setupUi(this);
}

LoginWindow::~LoginWindow()
{
    delete ui;
}

void LoginWindow::on_loginButton_clicked()
{
    QString username = ui->usernameLineEdit->text();
    QString password = ui->passwordLineEdit->text();

    if (validateCredentials(username, password)) {
        emit loginSuccess();
        this->close();
    } else {
        QMessageBox::warning(this, "登录失败", "用户名或密码错误");
    }
}

void LoginWindow::on_registerButton_clicked()
{
    QString username = ui->usernameLineEdit->text();
    QString password = ui->passwordLineEdit->text();

    saveUserData(username, password);
    QMessageBox::information(this, "注册成功", "用户注册成功");
}

bool LoginWindow::validateCredentials(const QString &username, const QString &password)
{
    QFile file("user_data.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return false;

    QTextStream in(&file);
    while (!in.atEnd()) {
        QString line = in.readLine();
        QStringList fields = line.split(" ");
        if (fields.size() == 2 && fields[0] == username && fields[1] == password) {
            return true;
        }
    }

    return false;
}

void LoginWindow::saveUserData(const QString &username, const QString &password)
{
    QFile file("user_data.txt");
    if (!file.open(QIODevice::Append | QIODevice::Text))
        return;

    QTextStream out(&file);
    out << username << " " << password << "\n";
}
